package org.wejob.nettytest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class HelloServer {
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup=new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup=new NioEventLoopGroup();
        new ServerBootstrap()
                //绑定线程池组
                .group(bossGroup,workGroup)
                //定义主reactor线程处理Handler
                .handler(new LoggingHandler(LogLevel.DEBUG))
                //3、选择服务器的ServerSocketChannel实现
                .channel(NioServerSocketChannel.class)
                //4、boss：负责处理连接；worker：处理读写，决定了worker(child)能执行哪些操作（handler）
                .childHandler(
                        //5、Channel代表和客户端进行数据读写的通道，Initializer初始化器，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                //添加具体的handler
                                ch.pipeline().addLast(new StringDecoder()); //17、将ByteBuf转换为字符串，然后给下一个处理器
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { //自定义handler
                                    @Override //读事件
                                    //18、执行channelRead()方法，打印hello
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println("WorkGroup thread name----"+Thread.currentThread().getName());
                                        System.out.println(msg);
                                        System.out.println(ctx.pipeline().names());
                                    }
                                });

                            }
                        })
                //6、绑定监听端口
                .bind(8888);
    }
}